package com.dankegongyu.lib.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.dankegongyu.lib.share.bean.DKShareImage;
import com.dankegongyu.lib.share.bean.DKShareObject;
import com.dankegongyu.lib.share.bean.DKShareWeb;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * https://developer.umeng.com/docs/66632/detail/66639
 *
 * @author WuPuquan
 * @version 1.0
 * @since 2017/11/13 11:10
 */

@SuppressWarnings("JavaDoc")
public class DKShareUtil {

    /**
     * 初始化
     */
    public static void init(Context context, String appKey, String channel, boolean isDebug) {
        // 参数：context, appKey, 渠道, UMConfigure.DEVICE_TYPE_PHONE, 传空即可
        if (!UMConfigure.getInitStatus()) {
            UMConfigure.init(context, appKey, channel, UMConfigure.DEVICE_TYPE_PHONE, "");
        }
        UMConfigure.setLogEnabled(isDebug);

        // 设置每次登录拉取确认界面，建议在application中初始化
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(context).setShareConfig(config);
    }

    public static void setWeixin(String appId, String appSecret) {
        // 参数：appId, appSecret
        PlatformConfig.setWeixin(appId, appSecret);
    }

    public static void setSinaWeibo(String appId, String appSecret, String url) {
        PlatformConfig.setSinaWeibo(appId, appSecret, url);
    }

    /**
     * 分享点击，适用于自定义分享页面
     *
     * @param shareMedia    分享平台，使用默认平台{@link DK_SHARE_MEDIA} 或 自定义
     * @param shareObject   分享内容
     * @param shareListener 分享回调
     */
    public static void share(@NonNull DK_SHARE_MEDIA shareMedia, DKShareObject shareObject, DKShareCallback shareListener) {
        share(shareMedia.getName(), shareObject, shareListener);
    }

    /**
     * 分享点击，适用于自定义分享页面
     *
     * @param platform      分享平台，使用默认平台{@link DK_SHARE_MEDIA} 或 自定义
     * @param shareObject   分享内容
     * @param shareListener 分享回调
     */
    public static void share(String platform, DKShareObject shareObject, DKShareCallback shareListener) {
        share(platform, shareObject, shareListener, null);
    }

    @SuppressWarnings("unchecked")
    public static <T extends DKShareObject> void shareDefault(final T shareObject, final DKShareCallback shareListener) {
        if (shareObject == null || shareObject.getActivity() == null) {
            return;
        }
        if (shareObject.getCustomPlatforms() != null) {
            List<DKShareButton> list = shareObject.getCustomPlatforms();
            for (DKShareButton shareButton : list) {
                if (DK_SHARE_MEDIA.contains(shareButton.platform)) {
                    throw new IllegalArgumentException("Share platform " + shareButton.platform + " is already defined，please use another name instead!");
                }
            }
        }
        DKShareDialog.with(shareObject, shareListener).show();
    }

    static void share(String platform, DKShareObject shareObject, DKShareCallback shareListener, @Nullable DKShareDialog shareDialog) {
        DK_SHARE_MEDIA dk_share_media = DK_SHARE_MEDIA.getSHARE_MEDIA(platform);
        SHARE_MEDIA share_media = DKShareMediaConverter.getShareMedia(dk_share_media);
        if (share_media == null) {
            // 说明是自定义的
            if (shareDialog != null) {
                shareDialog.dismiss();
            }
            if (shareListener != null) {
                shareListener.onStart(platform);
                shareListener.onResult(platform, true);
            }
        } else {
            Activity activity = shareObject.getActivity();
            ShareAction shareAction = new ShareAction(activity);
            shareAction.setPlatform(share_media);
            // web | 小程序
            if (shareObject.getShareMedia() == DKShareObject.DKMediaType.WEB) {
                DKShareWeb shareWeb = (DKShareWeb) shareObject;
                if (SHARE_MEDIA.WEIXIN == share_media && shareWeb.getMiniProgram() != null) {
                    // 小程序
                    shareAction.withMedia(DKUmMediaFactory.createUMMin(activity, shareWeb.getMiniProgram()));
                } else {
                    // web
                    shareAction.withMedia(DKUmMediaFactory.createUMWeb(shareWeb));
                }
            }
            // image
            else if (shareObject.getShareMedia() == DKShareObject.DKMediaType.IMAGE) {
                DKShareImage shareImage = (DKShareImage) shareObject;
                shareAction.withMedia(DKUmMediaFactory.createUMImage(shareImage));
                shareAction.withText(shareImage.getShareContent());
            }
            // text
            else if (shareObject.getShareMedia() == DKShareObject.DKMediaType.TEXT) {
                shareAction.withText(shareObject.getShareContent());
            }
            shareAction
                    .setCallback(new DKUMShareListener(platform, shareDialog, shareListener))
                    .share();
        }
    }

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    public static boolean isActivityFinishingOrDestroyed(Activity activity) {
        return activity == null || activity.isFinishing() || activity.isDestroyed();
    }

    /**
     * 处理微信QQ等客户端未安装的情况
     */
    public static boolean handlePlatformNotInstalled(Activity activity, DK_SHARE_MEDIA dk_share_media) {
        SHARE_MEDIA share_media = DKShareMediaConverter.getShareMedia(dk_share_media);
        return handlePlatformNotInstalled(activity, share_media);
    }

    /**
     * 处理微信QQ等客户端未安装的情况
     *
     * @param activity target Activity
     * @param platform 分享平台
     */
    static boolean handlePlatformNotInstalled(Activity activity, SHARE_MEDIA platform) {
        if (!UMShareAPI.get(activity).isInstall(activity, platform)) {
            String appName = "";
            switch (platform) {
                case WEIXIN:
                case WEIXIN_CIRCLE:
                    appName = activity.getString(R.string.dk_share_weixin);
                    break;
                case QQ:
//                case QZONE: // QQ空间有独立的App，包名跟QQ不一样，所以这里暂不提示了
                    appName = activity.getString(R.string.dk_share_qq);
                    break;
            }
            Toast.makeText(activity, String.format(activity.getString(R.string.dk_share_not_installed), appName), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    /**
     * dp转px
     *
     * @param dpValue dp值
     * @return px值
     */
    public static int dp2px(Context context, final float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 内存泄漏解决方案
     * 在使用分享或者授权的Activity的onDestroy()中调用下面的方法
     */
    public static void release(Context context) {
        if (context != null) {
            UMShareAPI.get(context).release();
        }
    }

    /**
     * QQ与新浪不需要添加Activity，但需要在使用QQ分享或者授权的Activity中的onActivityResult中调用本方法
     * 注意onActivityResult不可在fragment中实现，如果在fragment中调用登录或分享，需要在fragment依赖的Activity中实现
     *
     * @param activity
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public static void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        if (activity != null) {
            UMShareAPI.get(activity).onActivityResult(requestCode, resultCode, data);
        }
    }
}
